Page({
  /**
   * 页面的初始数据
   */
  data: {
    announcements: [],
    loading: true,
    page: 1,
    pageSize: 10,
    hasMore: true,
    statusBarHeight: 20, // 默认状态栏高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取系统信息设置状态栏高度
    this.getStatusBarHeight();
    this.getAnnouncements();
  },

  /**
   * 获取状态栏高度
   */
  getStatusBarHeight: function () {
    const that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          statusBarHeight: res.statusBarHeight,
        });
      },
    });
  },

  /**
   * 获取公告列表
   */
  getAnnouncements: function (isLoadMore = false) {
    const { page, pageSize } = this.data;
    console.log("正在获取公告列表, 页码:", page, "每页数量:", pageSize);

    // 获取用户信息
    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : 1; // 使用实际用户ID，默认为1

    console.log("获取公告列表使用用户ID:", userId);

    // 显示加载状态
    this.setData({
      loading: true,
    });

    // 调用API获取公告列表
    wx.request({
      url: `https://smartsound.top/api/v1/user/announcements?user_id=${userId}&page=${page}&page_size=${pageSize}`,
      method: "GET",
      success: (res) => {
        console.log("获取公告响应:", res.data);

        if (res.data && res.data.code === 0) {
          const announcementsData = res.data.data || {};
          const newAnnouncements = announcementsData.announcements || [];

          // 判断是否还有更多数据
          const hasMore =
            announcementsData.page < announcementsData.total_pages;

          this.setData({
            announcements: isLoadMore
              ? [...this.data.announcements, ...newAnnouncements]
              : newAnnouncements,
            loading: false,
            hasMore: hasMore,
          });
        } else {
          console.error("获取公告失败:", res.data);
          this.setData({
            loading: false,
          });
          wx.showToast({
            title: res.data.message || "获取公告失败",
            icon: "none",
          });
        }
      },
      fail: (error) => {
        console.error("请求公告接口失败:", error);
        this.setData({
          loading: false,
        });
        wx.showToast({
          title: "网络请求失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 查看公告详情
   */
  viewAnnouncementDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title;

    // 查找当前选择的公告数据
    const announcement = this.data.announcements.find(
      (item) => item.announcement_id === id
    );

    if (announcement) {
      // 将完整的公告数据转为JSON字符串传递给详情页
      const announcementStr = encodeURIComponent(JSON.stringify(announcement));

      // 跳转到公告详情页面，携带完整的公告数据
      wx.navigateTo({
        url: `/pages/announcements/detail/detail?id=${id}&title=${encodeURIComponent(
          title
        )}&announcementData=${announcementStr}`,
      });
    } else {
      // 如果未找到数据，只传递基本参数
      wx.navigateTo({
        url: `/pages/announcements/detail/detail?id=${id}&title=${encodeURIComponent(
          title
        )}`,
      });
    }
  },

  /**
   * 返回上一页
   */
  navigateBack: function () {
    wx.navigateBack();
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: true,
    });
    this.getAnnouncements();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.hasMore) {
      this.setData({
        page: this.data.page + 1,
      });
      this.getAnnouncements(true);
    }
  },
});
